package com.ymt.fmd.platform.formdesigner.parser.impl;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.fmd.platform.formdesigner.parser.AbstractJsParser;
import com.ymt.fmd.util.Const;

public class Json2htmlParser extends AbstractJsParser {

	/**
	 * parse modules json to html
	 * @parma type form type
	 * @param env environment variables
	 * @param arguments
	 * @return
	 */
	@Override
	public StringBuilder parseForm(String formtype, String env, String arguments) throws Exception {
		String templateName = realPath + fmdProperties.getModulesPathBase() + "/form/"+formtype+"/template.jsp."+this.skin+"-"+this.lang;
		File file = new File(templateName+".txt");
		/*InputStreamReader isr = new InputStreamReader(new FileInputStream(file), Const.ENCODING);
		BufferedReader reader = new BufferedReader(isr);
        char[] chars = new char[(int)file.length()];
        reader.read(chars);
		String template = String.valueOf(chars);
		reader.close();*/
		String template = FileUtils.readFileToString(file, Const.ENCODING);
		engine.put("formtemplate", template);
		StringBuilder cmd = new StringBuilder();
		cmd.append("(function(){")
			.append("  var env="+env+";")//make it local
			.append("  var arguments="+arguments+";")//make it local
			.append("  Parser.log('env='+JSON.stringify(env));")
			.append("  Parser.log('arguments='+JSON.stringify(arguments));")
			.append("  return Parser.parseForm('"+formtype+"', env, arguments);")
			.append("})();");
		logger.finer("parseForm function="+cmd);
		String html=(String)engine.eval(cmd.toString());//run
		logger.finer("parseModules return:\n"+html);
		return new StringBuilder(html);
	}
	
	/**
	 * parse all modules
	 */
	@Override
	public JSONObject parseModules(String moduleList, String props, String models) throws Exception {
		engine.eval("Parser.confs="+moduleList);
		engine.eval("Parser.props="+props);
		engine.eval("Parser.models="+models);
		engine.eval("Parser.log('Parser.confs='+JSON.stringify(Parser.confs))");
		engine.eval("Parser.log('Parser.props='+JSON.stringify(Parser.props))");
		engine.eval("Parser.log('Parser.models='+JSON.stringify(Parser.models))");
		engine.eval("var rtnmodules = Parser.parseModules(Parser.confs, Parser.props)");
		engine.eval("Parser.parseEvents()");
		String html=(String)engine.eval("rtnmodules");
		String generatedScripts=(String)engine.eval("Parser.generatedscript ? Parser.generatedscript : ''");
		String fmdv=(String)engine.eval("JSON.stringify(Parser.fmdv)");
		logger.finer("parseModules return html:\n"+html);
		logger.finer("parseModules return generated_scripts:\n"+generatedScripts);
		logger.finer("parseModules return fmdv:\n"+fmdv);
		JSONObject rtn = new JSONObject();
		rtn.put("html", html);
		rtn.put("generatedscript", generatedScripts);
		rtn.put("fmdv", fmdv);
		return rtn;
	}

	/**
	 * 将表单转为只读表单
	 * @param formdata
	 * @return
	 */
	@Override
	public String toRoVersion(String formdata) {
		com.alibaba.fastjson.JSONObject fd = com.alibaba.fastjson.JSONObject.parseObject(formdata);
		com.alibaba.fastjson.JSONObject formconf = fd.getJSONObject("formconf");
		com.alibaba.fastjson.JSONObject propconf = fd.getJSONObject("propconf");
		iterateChildrenCompToRo(formconf, propconf);
		return fd.toJSONString();
	}
	
	private void iterateChildrenCompToRo(com.alibaba.fastjson.JSONObject parent, com.alibaba.fastjson.JSONObject propconf) {
		JSONArray children = getChildrenComp(parent);
		if (children!=null) {
			for (int i=0; i<children.size(); i++) {
				com.alibaba.fastjson.JSONObject comp = children.getJSONObject(i);
				if ("control".equalsIgnoreCase(comp.getString("compType"))) {
					convertToPoutputByType(comp, propconf.getJSONObject(comp.getString("id")));
				} else {
					iterateChildrenCompToRo(comp, propconf);
				}
			}
		}
	}
	
	/**
	 * 获取子对象
	 * @param parent
	 * @return
	 */
	private JSONArray getChildrenComp(com.alibaba.fastjson.JSONObject parent) {
		if (parent.containsKey("tabs")) {
			return parent.getJSONArray("tabs");
		} else if (parent.containsKey("items")) {
			return parent.getJSONArray("items");
		} else {
			return null;
		}
	}
	
	private void convertToPoutputByType(com.alibaba.fastjson.JSONObject comp, 
			com.alibaba.fastjson.JSONObject conf) {
		String type = comp.getString("type");
		com.alibaba.fastjson.JSONObject orginConf = new com.alibaba.fastjson.JSONObject();
		orginConf.putAll(conf);
		if ("input".equalsIgnoreCase(type)) {
			getBasicPropPoutput(comp, conf, orginConf);
			comp.put("type", "p");
		} else if ("popupinput".equalsIgnoreCase(type)) {
			getBasicPropPoutput(comp, conf, orginConf);
			conf.put("databinding", orginConf.get("databinding-displayvalue"));
			comp.put("type", "p");
		} else if ("textarea".equalsIgnoreCase(type)) {
			getBasicPropPoutput(comp, conf, orginConf);
			comp.put("type", "p");
		} else if ("datepicker".equalsIgnoreCase(type)) {
			getBasicPropPoutput(comp, conf, orginConf);
			comp.put("type", "p");
		} else if ("datepickeropt".equalsIgnoreCase(type)) {
			getBasicPropPoutput(comp, conf, orginConf);
			comp.put("type", "p");
		} else if ("select".equalsIgnoreCase(type)) {
			getBasicPropPoutput(comp, conf, orginConf);
			conf.put("databinding", orginConf.get("databinding-displayvalue"));
			comp.put("type", "p");
		} else if ("radio".equalsIgnoreCase(type)) {
			conf.put("disabled", "1");
		} else if ("checkbox".equalsIgnoreCase(type)) {
			conf.put("disabled", "1");
		} else if ("checkboxgroup".equalsIgnoreCase(type)) {
			conf.put("disabled", "1");
		} else if ("button".equalsIgnoreCase(type)) {
			conf.put("disabled", "1");
		} else if ("dhxgrid".equalsIgnoreCase(type)) {
			conf.put("editable", "0");
			conf.put("allowImExport", "0");
			//change subgrid rows
			com.alibaba.fastjson.JSONArray gridsetting = conf.getJSONArray("gridsetting");
			if (gridsetting!=null && gridsetting.size()>0) {
				for (int i=0;i<gridsetting.size();i++) {
					com.alibaba.fastjson.JSONObject rowsetting = gridsetting.getJSONObject(i);
					rowsetting.put("readonly", "1");
				}
			}
		}
	}
	
	public void getBasicPropPoutput(com.alibaba.fastjson.JSONObject comp, 
			com.alibaba.fastjson.JSONObject conf,
			com.alibaba.fastjson.JSONObject orginConf) {
		conf.clear();
		String[] attrs = new String[]{"display", "hideLabel", "i18nname-en", "i18nname-zh", "i18ntip-en", "i18ntip-zh", "databinding"};
		for (String attr : attrs) {
			if (orginConf.containsKey(attr)) {
				conf.put(attr, orginConf.get(attr));
			}
		}
	}

}
